<?php

//UMA new
namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;
use Illuminate\Foundation\Auth\User as Authenticatable;

class Customer extends Authenticatable
{
    protected $fillable = [
        'temporary_member_id',
        'company_id',
        'api_token',
        'token_updated_at',
    ];


    protected $dates = [
        'token_updated_at',
    ];

    
    public function histories() {
        return $this->hasMany(CustomerHistory::class, 'customer_id');
    }

    public function company() {
        return $this->belongsTo(Company::class, 'company_id');
    }

    // protected $attributes = [
    //     'token_updated_at' => now()->toDateTimeString(),
    // ];
    
    /**
     * 判断token是否有效
     * トークンが有効であると判断する
     * @return boolean
     */
    public function invalidToken()
    {
        return now()->diffInMinutes($this->token_updated_at) > config('const.token_validate_time');
    }
    
    /**
     * 更新token
     * 更新 token
     * @return model
     */
    public function refreshToken()
    {
        $this->token = Str::random(64);
        $this->token_updated_at = now();
        return $this->save();
    }
    
    /**
     * 设置token
     * セットアップtoken
     * @param  mixed $value
     * @return void
     */
    public function setApiTokenAttribute($value)
    {
        if (self::where('api_token', $value)->doesntExist()) {
            $token = $value;
        } else {
            do {
                $token = Str::random(64);
            } while (self::where("api_token", $token)->exists());
        }

        $this->attributes['api_token'] = $token;
    }
    
    /**
     * scopeByToken
     *
     * @param  mixed $query
     * @param  mixed $token
     * @return query
     */
    public function scopeByToken($query, $token)
    {
        return $query->where('api_token', $token);
    }
    
    /**
     * scopeByMemberId
     *
     * @param  mixed $query
     * @param  mixed $temporary_member_id
     * @return query
     */
    public function scopeByMemberId($query, $temporary_member_id)
    {
        return $query->where('temporary_member_id', $temporary_member_id);
    }

    public static function boot() {
        parent::boot();
        static::creating(function($model) {
            $model->temporary_member_id = uniqid();
            $model->token_updated_at = now();
        });
    }
}
